﻿using System;
using System.Collections.Generic;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace App91
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            MyCanvas.PointerPressed += MyCanvas_PointerPressed;
            MyCanvas.PointerMoved += MyCanvas_PointerMoved;
            MyCanvas.PointerReleased += MyCanvas_PointerReleased;
            MyCanvas.PointerExited += MyCanvas_PointerReleased;
        }

        Windows.UI.Xaml.Shapes.Path _CurrentLine;
        void MyCanvas_PointerPressed(object sender, PointerRoutedEventArgs e)
        {
            var pointer = e.GetCurrentPoint(this);
            if (!pointer.Properties.IsLeftButtonPressed)
                return;
            _CurrentLine = new Windows.UI.Xaml.Shapes.Path()
            {
                Data = new PathGeometry { Figures = { new PathFigure { StartPoint = pointer.Position, Segments = { new PolyLineSegment() }, }, } },
                Stroke = new SolidColorBrush(Colors.Black),
                StrokeThickness = 4d,
            };
            MyCanvas.Children.Add(_CurrentLine);
        }

        void MyCanvas_PointerMoved(object sender, PointerRoutedEventArgs e)
        {
            var pointer = e.GetCurrentPoint(this);
            if (!pointer.Properties.IsLeftButtonPressed || _CurrentLine == null)
            {
                _CurrentLine = null;
                return;
            }
            var segments = (_CurrentLine.Data as PathGeometry).Figures.First().Segments.First() as PolyLineSegment;
            segments.Points.Add(pointer.Position);
        }

        void MyCanvas_PointerReleased(object sender, PointerRoutedEventArgs e)
        {
            _CurrentLine = null;
        }
    }
}
